import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/test'
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('../views/TestView.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue')
    },
    {
      path: '/forgot-password',
      name: 'forgot-password',
      component: () => import('../views/ForgotPasswordView.vue')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/UserProfileView.vue')
    },
    {
      path: '/my-articles',
      name: 'my-articles',
      component: () => import('../views/MyArticlesView.vue')
    },
    {
      path: '/community',
      name: 'community',
      component: () => import('../views/CommunityView.vue')
    },
    {
      path: '/community/article/:id',
      name: 'ArticleDetail',
      component: () => import('@/views/ArticleDetailView.vue')
    },
    {
      path: '/learning',
      name: 'learning',
      component: () => import('../views/LearningView.vue')
    },
    {
      path: '/ai-assistant',
      name: 'ai-assistant',
      component: () => import('../views/AIAssistantView.vue')
    },
    {
      path: '/course',
      name: 'course',
      component: () => import('../views/LearningView.vue')
    },
    {
      path: '/course/:id',
      name: 'course-detail',
      component: () => import('../views/CourseDetailView.vue')
    },
    {
      path: '/my-collect',
      name: 'my-collect',
      component: () => import('../views/MyCollectView.vue')
    },
    {
      path: '/video-study/:id',
      name: 'video-study',
      component: () => import('@/views/VideoStudyView.vue')
    },
    // 教师后台路由
    {
      path: '/teacher',
      component: () => import('../views/TeacherDashboard.vue'),
      children: [
        {
          path: '',
          redirect: '/teacher/analytics'
        },
        {
          path: 'dashboard',
          name: 'teacher-dashboard',
          component: () => import('../views/teacher/DashboardView.vue')
        },
        {
          path: 'courses',
          name: 'teacher-courses',
          component: () => import('../views/teacher/CoursesView.vue')
        },
        {
          path: 'community',
          name: 'teacher-community',
          component: () => import('../views/teacher/CommunityManageView.vue')
        },
        {
          path: 'analytics',
          name: 'teacher-analytics',
          component: () => import('../views/teacher/AnalyticsView.vue')
        },
        {
          path: 'messages',
          name: 'teacher-messages',
          component: () => import('../views/teacher/MessagesView.vue')
        },
        {
          path: 'settings',
          name: 'teacher-settings',
          component: () => import('../views/teacher/SettingsView.vue')
        },
        {
          path: 'create-course',
          name: 'teacher-create-course',
          component: () => import('../views/teacher/CreateCourse.vue')
        },
        {
          path: 'courses/edit/:id',
          name: 'teacher-edit-course',
          component: () => import('../views/teacher/EditCourse.vue')
        },
        {
          path: 'courses/:id/chapters',
          name: 'teacher-course-chapters',
          component: () => import('../views/teacher/CourseChaptersView.vue')
        },
        {
          path: 'course-classify',
          name: 'TeacherCourseClassifyManage',
          component: () => import('@/views/teacher/CourseClassifyManage.vue')
        }
      ]
    },
    {
      path: '/user/update',
      name: 'UserUpdate',
      component: () => import('@/views/UserUpdateView.vue'),
      meta: {
        requiresAuth: true
      }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查本地存储中的token
  const token = localStorage.getItem('token')
  
  // 不需要登录的路由
  const publicRoutes = ['/login', '/register', '/forgot-password']
  
  // 如果是公开路由，直接放行
  if (publicRoutes.includes(to.path)) {
    next()
    return
  }
  
  // 如果没有token，重定向到登录页
  if (!token) {
    ElMessage.warning('请先登录')
    next('/login')
    return
  }
  
  // 获取用户信息
  let userInfo
  try {
    userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  } catch (e) {
    console.error('解析用户信息失败', e)
    ElMessage.error('用户信息解析失败，请重新登录')
    next('/login')
    return
  }
  
  // 根据用户角色控制访问权限
  const userRole = userInfo.roles?.[0] // 获取用户角色
  
  // 教师后台路由权限控制
  if (to.path.startsWith('/teacher')) {
    if (userRole !== 'TEACHER' && userRole !== 'ADMIN') {
      ElMessage.error('没有访问教师后台的权限')
      next('/')
      return
    }
  }
  
  // 管理员路由权限控制
  if (to.path.startsWith('/admin')) {
    if (userRole !== 'ADMIN') {
      ElMessage.error('没有访问管理员后台的权限')
      next('/')
      return
    }
  }
  
  // 学生专属路由权限控制
  if (to.path.startsWith('/student')) {
    if (userRole !== 'STUDENT') {
      ElMessage.error('没有访问学生页面的权限')
      next('/')
      return
    }
  }
  
  next()
})

// 全局后置钩子，处理API返回的权限错误
router.afterEach((to, from) => {
  // 监听全局错误处理
  window.addEventListener('unhandledrejection', (event) => {
    if (event.reason?.response?.data?.message === '没有权限') {
      ElMessage.error('没有权限访问该功能')
      event.preventDefault()
    }
  })
})

export default router
